{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ba8ec17f-f7e6-4f2d-95a9-8b38f5d9a103",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Test anomaly-score-unsupervised\n",
    "This notebook smoketests the anomaly-score-unsupervised component"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76b2d0b4-0e99-41b3-9804-5b1c4a8db1cf",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Start the anomaly-score-unsupervised notebook using ipython. This will create a local service on port 8080\n",
    "\n",
    "import subprocess\n",
    "sp  = subprocess.Popen([\"ipython\",\"../anomaly-score-unsupervised.ipynb\"])\n",
    "sp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f0843b3-d2a6-461a-9575-fd44a1b69fad",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Give the service some time to start\n",
    "\n",
    "import time\n",
    "\n",
    "print(\"Waiting for service to start...\")\n",
    "time.sleep(10)\n",
    "print(\"..hope it is started now...\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c91a4d4-8629-4a55-a530-6dd400e6eef3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import json\n",
    "import pickle\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "170d6e01-537f-4442-bf1d-168e611a7acd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# e-serialize test data\n",
    "\n",
    "with open('watsoniotp.healthy.phase_aligned.pickle','rb') as file_object:\n",
    "    raw_data = file_object.read()\n",
    "    data_healthy = pickle.loads(raw_data, encoding='latin1')\n",
    "\n",
    "with open('watsoniotp.broken.phase_aligned.pickle','rb') as file_object:\n",
    "    raw_data = file_object.read()\n",
    "    data_broken = pickle.loads(raw_data, encoding='latin1')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d7081b6-2de9-47d5-a00e-59348789c5b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# inspect 3D time series of healthy data\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "fig, ax = plt.subplots(num=None, figsize=(14, 6), dpi=80, facecolor='w', edgecolor='k')\n",
    "size = len(data_healthy)\n",
    "#ax.set_ylim(0,energy.max())\n",
    "ax.plot(range(0,size), data_healthy[:,0], '-', color='blue', animated = True, linewidth=1)\n",
    "ax.plot(range(0,size), data_healthy[:,1], '-', color='red', animated = True, linewidth=1)\n",
    "ax.plot(range(0,size), data_healthy[:,2], '-', color='green', animated = True, linewidth=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed0397b5-02ce-4aac-8972-d5b7406bcd71",
   "metadata": {},
   "outputs": [],
   "source": [
    "# inspect 3D time series of broken data\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "fig, ax = plt.subplots(num=None, figsize=(14, 6), dpi=80, facecolor='w', edgecolor='k')\n",
    "size = len(data_broken)\n",
    "#ax.set_ylim(0,energy.max())\n",
    "ax.plot(range(0,size), data_broken[:,0], '-', color='blue', animated = True, linewidth=1)\n",
    "ax.plot(range(0,size), data_broken[:,1], '-', color='red', animated = True, linewidth=1)\n",
    "ax.plot(range(0,size), data_broken[:,2], '-', color='green', animated = True, linewidth=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f07db00f-f6d9-4c18-9af4-fce620e60299",
   "metadata": {},
   "outputs": [],
   "source": [
    "# prepare for frequency spectrum comparison by applying fft\n",
    "\n",
    "import numpy as np\n",
    "data_healthy_fft = np.fft.fft(data_healthy)\n",
    "data_broken_fft = np.fft.fft(data_broken)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60c96fbb-beb4-40e7-974e-08d5158a8a9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot frequency spectrum for healthy data\n",
    "\n",
    "fig, ax = plt.subplots(num=None, figsize=(14, 6), dpi=80, facecolor='w', edgecolor='k')\n",
    "size = len(data_healthy_fft)\n",
    "ax.plot(range(0,size), data_healthy_fft[:,0].real, '-', color='blue', animated = True, linewidth=1)\n",
    "ax.plot(range(0,size), data_healthy_fft[:,1].imag, '-', color='red', animated = True, linewidth=1)\n",
    "ax.plot(range(0,size), data_healthy_fft[:,2].real, '-', color='green', animated = True, linewidth=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "049f61a7-0d37-4c06-a514-e09ff777dea7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot frequency spectrum for broken data\n",
    "\n",
    "fig, ax = plt.subplots(num=None, figsize=(14, 6), dpi=80, facecolor='w', edgecolor='k')\n",
    "size = len(data_healthy_fft)\n",
    "ax.plot(range(0,size), data_broken_fft[:,0].real, '-', color='blue', animated = True, linewidth=1)\n",
    "ax.plot(range(0,size), data_broken_fft[:,1].imag, '-', color='red', animated = True, linewidth=1)\n",
    "ax.plot(range(0,size), data_broken_fft[:,2].real, '-', color='green', animated = True, linewidth=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4e25b8d-9958-4fd3-8e0e-400fce9b3f4a",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "# convert test data from numpy to json (to be used when calling th web service via HTTP)\n",
    "\n",
    "data_healthy = data_healthy.tolist()\n",
    "data_healthy = json.dumps(data_healthy)\n",
    "data_broken = data_broken.tolist()\n",
    "data_broken = json.dumps(data_broken)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d00bef91-b37b-439e-bafb-0b3de02fc5e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize http client parameters\n",
    "url = \"http://localhost:8080/send_data\"\n",
    "headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74104612-49dc-406e-af84-c0f446f859e0",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "# test with healthy data\n",
    "for _ in range(3):\n",
    "    r = requests.post(url, data=data_healthy, headers=headers)\n",
    "    assert(r.status_code==200)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3d0797a-892c-4c7f-970d-16f7dd2b39c0",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "#test with broken data\n",
    "\n",
    "r = requests.post(url, data=data_broken, headers=headers)\n",
    "assert(r.status_code==200)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "114f8059-3461-418e-b99a-4ce285486c75",
   "metadata": {},
   "outputs": [],
   "source": [
    "# retest with healthy data\n",
    "\n",
    "for _ in range(3):\n",
    "    r = requests.post(url, data=data_healthy, headers=headers)\n",
    "    assert(r.status_code==200)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72b35a13-3dc5-4461-9126-08e3d1328085",
   "metadata": {},
   "outputs": [],
   "source": [
    "# display loss (reconstruction) history\n",
    "\n",
    "from IPython.display import Image\n",
    "Image(\"http://localhost:8080/get_loss_as_image.png\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d784ba8b-67fe-4b44-8ecf-7cf558d5953d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# stop service process\n",
    "\n",
    "import psutil\n",
    "\n",
    "pids = psutil.pids()\n",
    "\n",
    "for pid in pids:\n",
    "    if psutil.pid_exists(pid):\n",
    "        p = psutil.Process(pid)\n",
    "        if any(\"anomaly-score-unsupervised.ipynb\" in s for s in p.cmdline()):\n",
    "            print(p.kill())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
